import os
from pyglet.gl import *
from _global import enum

class Texture(object):
	Type = enum(		#Specify how to expect args
		'NULL',			#0 - unspecified
		'SQUARE',		#1 - use coord list for a quad counterclockwise: 0,0 1,0 1,1 0,1
		'GRID',			#2 - generate coord list for quads based on args ROWS and COLS
		'LIST'			#3 - args = list of tuples for calling sequentially
	)
	def __init__(self):
		self.coord = None
		self.ref = None
		self.type = Texture.Type.NULL
	
	def __str__(self):
		return "id = " + str(self.ref.id) + "\ncoords = " + str(self.coord) + "\n"
	
	@property
	def id(self):
		return self.ref.id
	@property
	def target(self):
		return self.ref.target

class TextureList(object):
	def __init__(self):
		self.tex = []		#List of Texture's for attaching to vertices
	
	def __getitem__(self, index):
		return self.tex[index]
	def __setitem__(self, key, item):
		self.tex[key] = item
		
	def loadTex(self, filename, coordType=0, args=[]):
		t = Texture()
		t.type = coordType
		
		pic = pyglet.image.load("img" + os.sep + filename)
		texture = pic.get_texture()
		ix = pic.width
		iy = pic.height
		rawimage = pic.get_image_data()
		format = 'RGBA'
		pitch = rawimage.width * len(format)
		myimage = rawimage.get_data(format, pitch)
		
		t.ref = texture

		glBindTexture(texture.target, texture.id)
		
		glPixelStorei(GL_UNPACK_ALIGNMENT,1)
		glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, myimage) 
		#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
		#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
		#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
		#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
		
		numArgs = len(args)
		
		#Figure out all the textures coordinates based on the type
		if coordType == Texture.Type.SQUARE:
			t.coord = [(0., 1.), (1., 1.), (1., 0.), (0., 0.)]
		elif coordType == Texture.Type.GRID:
			if not numArgs == 2:
				raise Exception("Expected 2 args for GRID type, got", numArgs)
			
			rowHeight = 1. / args[0]
			colWidth = 1. / args[1]
			t.coord = []
			
			for r in range(args[1] - 1, -1, -1):		#texture T, reads from 1 to 0
				for c in range(args[0]):				#texture S
					t.coord.append((c * colWidth, r * rowHeight + rowHeight))
					t.coord.append((c * colWidth + colWidth, r * rowHeight + rowHeight))
					t.coord.append((c * colWidth + colWidth, r * rowHeight))
					t.coord.append((c * colWidth, r * rowHeight))
			
		elif coordType == Texture.Type.LIST:
			if numArgs < 3:
				raise Exception("Expected at least 3 args for LIST type, got", numArgs)
			t.coord = args
		
		self.tex.append(t)		#Add the new texture to the list